﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Linq;
using System.Security.Cryptography;
using DevExpress.XtraEditors;
using DevExpress.XtraBars;
using System.IO;

namespace INHOADON_TAMVAN
{
    public delegate void DangNhapEventHandler(object sender, Boolean e);

    public partial class XtraUserControl1 : DevExpress.XtraEditors.XtraUserControl
    {
        public event DangNhapEventHandler dangNhapThanhCong;

        public XtraUserControl1()
        {
            InitializeComponent();

            // Key for encryption
            SystemInfo.pub_KeyForEncrytion = "ThuPhiVeSinh";

            // Server name
            SystemInfo.pub_ServerName = System.Configuration.ConfigurationManager.AppSettings["serverName"];
            txtTenMayChu.Text = SystemInfo.pub_ServerName;

            // Database name
            SystemInfo.pub_DatabaseName = System.Configuration.ConfigurationManager.AppSettings["databaseName"];
            txtTenCSDL.Text = SystemInfo.pub_DatabaseName;

            // Database user name
            SystemInfo.pub_UserName = System.Configuration.ConfigurationManager.AppSettings["databaseUserName"];
            txtDatabaseUser.Text = SystemInfo.pub_UserName;

            // Application user password
            if (System.Configuration.ConfigurationManager.AppSettings["databaseUserPassword"] != null &&
                SystemInfo.pub_KeyForEncrytion != null)
            {
                   SystemInfo.pub_UserPassword = EncryptionUtility.DecryptString(
                System.Configuration.ConfigurationManager.AppSettings["databaseUserPassword"],
                SystemInfo.pub_KeyForEncrytion);
            txtDatabaseUserPassword.Text = SystemInfo.pub_UserPassword;
            }
            //Application first run 
            //SystemInfo.pub_FirtsRun = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["firstRun"]);


            // Application user name
            SystemInfo.pub_AppUserName = System.Configuration.ConfigurationManager.AppSettings["applicationUsername"];
            txtTenDangNhap.Text = SystemInfo.pub_AppUserName;

            // Application user_password
            if (System.Configuration.ConfigurationManager.AppSettings["applicationUserPassword"] != null &&
               SystemInfo.pub_KeyForEncrytion != null)
            {
                SystemInfo.pub_AppUserPassword = EncryptionUtility.DecryptString(
                    System.Configuration.ConfigurationManager.AppSettings["applicationUserPassword"],
                    SystemInfo.pub_KeyForEncrytion);
                txtMatKhau.Text = SystemInfo.pub_AppUserPassword;
            }

            // Connection string
            SystemInfo.pub_ConnString = "user id = " + SystemInfo.pub_UserName + ";" +
                                            "password = " + SystemInfo.pub_UserPassword + ";" +
                                            "server = " + SystemInfo.pub_ServerName + ";" +
                                            "Trusted_Connection = no;" +
                                            "database = " + SystemInfo.pub_DatabaseName + ";" +
                                            "connection timeout=20";
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            Boolean dangNhapFlag = false;

            //Test connection
            SqlConnection myConnection = new SqlConnection(SystemInfo.pub_ConnString);

            try
            {
                myConnection.Open();

                 DataClasses1DataContext db = new DataClasses1DataContext(SystemInfo.pub_ConnString);

                // query database - CSDL chua co bang nguoi dung; co bang pass
                var nguoiDung = from c in db.NGUOI_DUNGs select c;
                 
                //var nguoiDung = db.passes;

                Cursor.Current = Cursors.WaitCursor;

                foreach (var c in nguoiDung)
                {
                    if (c.ND_Ten.Trim() == txtTenDangNhap.Text.Trim())
                    {
                        if (EncryptionUtility.DecryptString(c.ND_MatKhau, SystemInfo.pub_KeyForEncrytion) == txtMatKhau.Text)
                        {
                            dangNhapFlag = true;

                            // Thông tin phân quyền
                            SystemInfo.pub_QuyenSuDung = c.ND_QuyenSuDung;

                            SystemInfo.pub_AppUserFullName = c.ND_TenDayDu;
                        }
                        break;
                    }

                    //if (c.id.Trim() == txtTenDangNhap.Text.Trim())
                    //{
                    //    MD5_Luan.MD5_Luan md5Obj = new MD5_Luan.MD5_Luan();

                    //    if (md5Obj.MD5(txtMatKhau.Text) == c.pass1)
                    //    {
                    //        dangNhapFlag = true;

                    //        // Thông tin phân quyền
                    //        //SystemInfo.pub_QuyenSuDung = c.ND_QuyenSuDung;

                    //        //SystemInfo.pub_AppUserFullName = c.ND_TenDayDu;
                    //    }
                    //    break;
                    //}
                }

                if (dangNhapFlag == true)
                {
                     // Application user name
                    SystemInfo.pub_AppUserName = txtTenDangNhap.Text;

                    // Application user_password
                    SystemInfo.pub_AppUserPassword = txtMatKhau.Text;

                    if (checkEdit1.Checked == true)
                    {
                        // Lưu vào app.config            
                        AppConfigFileSetting.UpdateAppSettings("applicationUsername",
                            SystemInfo.pub_AppUserName);

                        //Encrypt the password
                        string EncryptedAppUserPassword = EncryptionUtility.EncryptString(
                                SystemInfo.pub_AppUserPassword, SystemInfo.pub_KeyForEncrytion);
                        AppConfigFileSetting.UpdateAppSettings("applicationUserPassword", EncryptedAppUserPassword);

                        //Encrypt the password - Quan ly hoa don cua LUAN
                        //MD5_Luan.MD5_Luan md5Obj = new MD5_Luan.MD5_Luan();

                        //string EncryptedAppUserPassword = md5Obj.MD5(txtMatKhau.Text);
                        //AppConfigFileSetting.UpdateAppSettings("applicationUserPassword", EncryptedAppUserPassword);
                    }

                    else
                    {
                        // Lưu giá trị rỗng vào app.config            
                        AppConfigFileSetting.UpdateAppSettings("applicationUsername", " ");

                        //Encrypt the password
                        AppConfigFileSetting.UpdateAppSettings("applicationUserPassword", " ");
                    }

                    Cursor.Current = Cursors.Default;

                    // Raised the event Đăng nhập thành công
                    if (dangNhapThanhCong != null)
                    {
                        dangNhapThanhCong(this, true);
                    }
                }

                else
                {
                    XtraMessageBox.Show("Đăng nhập thất bại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cursor.Current = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Kết nối không thành công. \n" + ex.Message.ToString() , "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                myConnection.Close();
            }
        }

        private void btKetNoi_Click(object sender, EventArgs e)
        {
            if (lblTenMayChu.Visible == false)
            {
                lblTenMayChu.Visible = true;
                txtTenMayChu.Visible = true;
                lblTaiKhoan.Visible = true;
                txtDatabaseUser.Visible = true;
                lblMatKhau.Visible = true;
                txtDatabaseUserPassword.Visible = true;
                lblTenCSDL.Visible = true;
                txtTenCSDL.Visible = true;

                txtTenMayChu.Focus();
            }

            else if (lblTenMayChu.Visible == true)
            {
                // Server name
                SystemInfo.pub_ServerName = txtTenMayChu.Text;

                // Database name
                SystemInfo.pub_DatabaseName = txtTenCSDL.Text;

                // Database username
                SystemInfo.pub_UserName = txtDatabaseUser.Text;

                // User password
                SystemInfo.pub_UserPassword = txtDatabaseUserPassword.Text;

                // Connection string
                //SystemInfo.pub_ConnString = //"Data Source=" + SystemInfo.pub_ServerName + ";Initial Catalog=" + SystemInfo.pub_DatabaseName + ";Integrated Security=True";
                //"Data Source =" + SystemInfo.pub_ServerName + ";" + "Database = " + SystemInfo.pub_DatabaseName + ";" +
                //                        "Persist Security Info=True;";
                SystemInfo.pub_ConnString = "Data Source = " + SystemInfo.pub_ServerName + ";" + "Database = " + SystemInfo.pub_DatabaseName + ";" +
                                                "Integrated Security=false;" +
                                                "User ID = " + SystemInfo.pub_UserName + ";" +
                                                "Password = " + SystemInfo.pub_UserPassword;
                    //"Data Source =" + SystemInfo.pub_ServerName + ";" +
                    //                        "Initial Catalog=" + SystemInfo.pub_DatabaseName + ";Persist Security Info=True;User ID=" + SystemInfo.pub_UserName +
                    //                        "; Password = " + SystemInfo.pub_UserPassword;
                    //Data Source=.;AttachDbFilename=D:\dataCSP\QLHD_CSP.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True
                            //"Data Source =" + SystemInfo.pub_ServerName + ";" + "Database = " + SystemInfo.pub_DatabaseName + ";" +
                            //                        "Persist Security Info=True;";
                            //"user id = " + SystemInfo.pub_UserName + ";" +
                            //"password = " + SystemInfo.pub_UserPassword + ";" +
                            //"server = " + SystemInfo.pub_ServerName + ";" +
                            //"Trusted_Connection = no;;connection timeout=20";

                //Test connection
                SqlConnection myConnection = new SqlConnection(SystemInfo.pub_ConnString);

                try
                {
                    myConnection.Open();

                    XtraMessageBox.Show("Kết nối thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    String newConnecionString = "Data Source = " + txtTenMayChu.Text + ";" + "Database = " + SystemInfo.pub_DatabaseName + ";" +
                                                "Integrated Security=True;" +
                                                "Initial Catalog = " + "ThuPhiVeSinh" + ";" +
                                                "User ID = " + txtDatabaseUser.Text + ";" +
                                                "Password = " + txtDatabaseUserPassword.Text;

                    //Write to app.config
                    AppConfigFileSetting.UpdateConnectionStringValue(newConnecionString);
                    AppConfigFileSetting.UpdateAppSettings("serverName", SystemInfo.pub_ServerName);
                    AppConfigFileSetting.UpdateAppSettings("databaseName", SystemInfo.pub_DatabaseName);

                    //this.createDatabaseFirst();
                    //this.MoveFile();
                    //AppConfigFileSetting.UpdateAppSettings("databaseUsername", SystemInfo.pub_UserName);

                    //Encrypt the password
                    string EncryptedDatabaseUserPassword = EncryptionUtility.EncryptString(SystemInfo.pub_UserPassword,
                                                                             SystemInfo.pub_KeyForEncrytion);
                    AppConfigFileSetting.UpdateAppSettings("databaseUserPassword", EncryptedDatabaseUserPassword);


                    //Encrypt the password - LUAN
                    //MD5_Luan.MD5_Luan md5Obj = new MD5_Luan.MD5_Luan();

                    //string EncryptedAppUserPassword = md5Obj.MD5(txtMatKhau.Text);
                    //AppConfigFileSetting.UpdateAppSettings("applicationUserPassword", EncryptedAppUserPassword);



                    lblTenMayChu.Visible = false;
                    txtTenMayChu.Visible = false;
                    lblTenCSDL.Visible = false;
                    txtTenCSDL.Visible = false;
                    lblTaiKhoan.Visible = false;
                    txtDatabaseUser.Visible = false;
                    lblMatKhau.Visible = false;
                    txtDatabaseUserPassword.Visible = false;
                    txtTenDangNhap.Focus();
                }
                catch (Exception)
                {
                    throw;
                }
               
            }
        }

        private void txtDatabaseUserPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btKetNoi.PerformClick();
            }
            
        }

        private void checkEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btDangNhap.Focus();
            }  
        }


        private void createDatabaseFirst(string conn)
        {
            if (SystemInfo.pub_FirtsRun)
            {
                try
                {
                    string sql = @"IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'QLHD_CSP') begin RESTORE DATABASE [QLHD_CSP] FROM  DISK = N'C:\Program Files\Trung tam cong nghe phan mem thanh pho can tho\In Hoa Don GTGT\QLHD_CSP.bak' WITH  FILE = 1,  NOUNLOAD,  STATS = 10 end";
                    SqlConnection connection = new SqlConnection();
                    connection.ConnectionString = conn;
                    connection.Open();
                    SqlCommand comand = new SqlCommand(sql, connection);
                    comand.ExecuteNonQuery();
                    AppConfigFileSetting.UpdateFirstRunValue(false);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        //private vo
        private bool MoveFile()
        {
            if(!Directory.Exists(@"D:\DataCSp\"))
            {
                Directory.CreateDirectory(@"D:\DataCSp\");
                return true;
            }
            else 
                return false;
        }
            //{
            //    //string sourceFile = @"C:\Program Files\Trung tam cong nghe phan mem thanh pho can tho\In Hoa Don GTGT\QLHD_CSP.bak";
            //    string sourceFile = "QLHD_CSP.bak";
            //    string sourceFileMDF = "QLHD_CSP.mdf";
            //    string sourceFileLDF = "QLHD_CSP_log.ldf";



            //    string destinationFile = @"D:\DataCSP\QLHD_CSP.bak";
            //    string destinationFileMDF = @"D:\DataCSP\QLHD_CSP.mdf";
            //    string destinationFileLDF = @"D:\DataCSP\QLHD_CSP_log.ldf";

            //    if (!Directory.Exists(@"D:\dataCSP\"))
            //    {
            //        Directory.CreateDirectory(@"D:\DataCSP\");
            //        File.Move(sourceFile,@"D:\DataCSP\");
            //        File.Move(sourceFileMDF, @"D:\DataCSP\");
            //        File.Move(sourceFileLDF, @"D:\DataCSP\");
            //        //System.IO.File.Move(sourceFile, destinationFile);
            //    }

            // To move a file or folder to a new location:
            //System.IO.File.Move(sourceFile, destinationFile);

            // To move an entire directory. To programmatically modify or combine 
            // path strings, use the System.IO.Path class.
            //System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
        
    }
}
